// function add(a: number, b: number) { 
//   return a + b;
// }

// type Add = (a: number, b: number) => number;
interface Add { 
  (a: number, b: number): number;
}

const add: Add = (a, b) => a + b;

// type User = {
//   userId: number;
//   name: string;
//   info: (name: string) => string;
// }

interface User {
  userId: number;
  name: string;
  info: (name: string) => string;
}

let obj:User = {
  userId: 1,
  name: 'John',
  info: (a) => { 
    return "hello";
  }
}

// type Log = (userId: number, message?: string) => void;
interface Log { 
  (userId: number, message?: string): void;
}

const log: Log = function(id: number) { 
  console.log(id)
}

// type SumFn = (...numbers: number[]) => number;

// const sum: SumFn = (...numbers) => numbers.reduce((acc, cur) => acc + cur, 0);

function sumResult(...numbers: number[]) { 
  return numbers.reduce((acc, cur) => acc + cur, 0);
}

type SumFn = typeof sumResult;


// callback的调用签名
type ErrorCB = (err: Error | null, result: string) => void;

type HandleData = (data: string, cb: ErrorCB) => void;

// 带回调函数的复杂函数
function handleData(data: string, callback:ErrorCB): void { 
  // 模拟处理数据
  if (data === "error") { 
    callback(new Error("error"), "");
  }
  else {
    callback(null, "handled " + data);
  }
}

// const handleData: HandleData = (data, callback) => { 
//   // 模拟处理数据
//   if (data === "error") { 
//     callback(new Error("error"), "");
//   }
//   else {
//     callback(null, "handled " + data);
//   }
// }

type HandleData2 = typeof handleData;


interface Person { 
  name: string;
  handle: HandleData;
}
const p: Person = {
  name: "John",
  handle: (data, cb) => { 
    if (data === "error") { 
      cb(new Error("error"), "");
    }
    else {
      cb(null, "handled " + data);
    }
  }
}


// 上下文类型推导
type Fn = (index: number) => void;

function times(fn: Fn, n: number) { 
  for (let i = 0; i < n; i++) { 
    fn(i);
  }
}

const f = (n:number) => console.log(n);

times(f, 4)